<script setup lang="ts">
/**
 * 菜单权限管理模态框组件
 * @module MenuAuthModal
 * @desc 用于角色菜单权限的分配管理
 * @author YourName
 * @date 2025-04-23
 */

import { computed, shallowRef, watch, toRaw } from 'vue';
import { $t } from '@/locales';
import { fetchGetAllPages, fetchGetMenuTree, getRoleResourceId, updateRoleResourceInfo } from '@/service/api';

// 组件配置
defineOptions({ name: 'MenuAuthModal' });

interface Props {
  roleId: number;
}

const props = defineProps<Props>();
const visible = defineModel<boolean>('visible', { default: false });

// 响应式数据
const home = shallowRef('');
const pages = shallowRef<string[]>([]);
const tree = shallowRef<Api.SystemManage.MenuTree[]>([]);
const checks = shallowRef<number[]>([]); // 存储纯数字ID

// 核心优化点1：使用Element Plus Tree的完整选中状态管理
const treeRef = shallowRef();

// 获取已配置权限（优化数据格式）
async function getChecks() {
  const { data } = await getRoleResourceId(props.roleId);
  checks.value = data.flatMap(extractIds); // 立即转换为纯数字数组
}

// 核心优化点2：递归提取ID（处理Proxy嵌套结构）
const extractIds = (items: any[]): number[] => {
  return items.flatMap(item => {
    if (typeof item === 'number') return [item];
    
    const raw = toRaw(item);
    if (raw?.id && typeof raw.id === 'number') {
      return [raw.id, ...(raw.children?.length ? extractIds(raw.children) : [])];
    }
    return [];
  });
};

// 提交处理（优化参数构造）
async function handleSubmit() {
  try {
    // 获取完整选中节点（包含半选父节点）
    const checkedKeys = [
      ...treeRef.value.getCheckedKeys(),    // 全选节点
      ...treeRef.value.getHalfCheckedKeys() // 半选父节点
    ];

    const params: Api.SystemManage.RoleParamParams = {
      roleId: props.roleId,
      resourceId: [...new Set(checkedKeys)] // 去重处理
    };

    // await updateRoleResourceInfo(params);
    window.$message?.success?.($t('common.modifySuccess'));
    closeModal();
  } catch (error) {
    window.$message?.error?.(error.message);
  }
}

// 初始化流程优化
async function init() {
  try {
    await Promise.all([
      getHome(),
      getPages(),
      fetchMenuTree(),
      getChecks()
    ]);
  } catch (error) {
    window.$message?.error?.(error.message);
    closeModal();
  }
}

// 获取菜单树（添加类型断言）
async function fetchMenuTree() {
  const { data } = await fetchGetMenuTree();
  tree.value = data as Api.SystemManage.MenuTree[];
}

// 关闭模态框时重置状态
function closeModal() {
  visible.value = false;
  checks.value = [];
  tree.value = [];
}

watch(visible, val => val && init());
</script>

<template>
  <ElDialog 
    v-model="visible" 
    :title="$t('common.edit') + $t('page.manage.role.menuAuth')" 
    preset="card" 
    class="w-480px"
  >
    <!-- 首页选择器 -->
    <div class="flex-y-center gap-16px pb-12px">
      <div>{{ $t('page.manage.menu.home') }}</div>
      <ElSelect 
        v-model="home" 
        :options="pages.map(p => ({ label: p, value: p }))" 
        size="small" 
        class="w-160px"
      />
    </div>

    <!-- 树形控件优化 -->
    <ElTree
      ref="treeRef"
      :data="tree"
      :default-checked-keys="checks"
      node-key="id"
      show-checkbox
      check-strictly
      highlight-current
      class="h-280px"
      :props="{
        label: 'menuName',
        children: 'children'
      }"
    />

    <template #footer>
      <ElSpace class="w-full justify-end">
        <ElButton size="small" @click="closeModal">
          {{ $t('common.cancel') }}
        </ElButton>
        <ElButton type="primary" size="small" @click="handleSubmit">
          {{ $t('common.confirm') }}
        </ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>